<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class SwaggerPhp extends Command {

    private $filename;
    private $apifox_token;
    private $projectid;

    public function __construct() {
        parent::__construct();
        $this->filename = public_path('swagger-ui').'/'.config('app.name').'.json';
        $this->apifox_token = 'APS-eJjcplMeCI6YTaSGcZDBjrhYy4R4GC08';       // zwp 
        $this->projectid = '3058269';
    }

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swagger:apifox';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成api文档&同步至apifox';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle() {
        exec("./vendor/bin/openapi app -f json -o {$this->filename}");
        dump(sprintf('openapi文件路径: %s', $this->filename));
        if (!file_exists($this->filename)) {
            dd('文件不存在');
        }
        $url = "https://api.apifox.cn/api/v1/projects/{$this->projectid}/import-data";
        $headers = [
            'X-Apifox-Version'      => '2022-11-16',
            'Authorization'         => "Bearer {$this->apifox_token}",
        ];
        $data = [
            'importFormat'          => 'openapi',
            "apiOverwriteMode"      => "methodAndPath",     // merge
            "schemaOverwriteMode"   => "name",              // merge
            "syncApiFolder"         => true,
            'data'                  => json_encode(json_decode(file_get_contents($this->filename), true)),
        ];
        $resp = Http::withHeaders($headers)->post($url, $data)->json();
        // dump(json_encode($resp));
        dump("更新结果: {$resp['success']}, 更新内容:", $resp['data']['apiCollection']);

        return Command::SUCCESS;
    }
}
